/*
 * Copyright 2019-2029 geekidea(https://github.com/geekidea)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.jingxing.controller;

import com.jingxing.config.ApiResult;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.region.Region;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 上传控制器
 *
 * @author yxs
 * @date 2020-10-23
 */
@Slf4j
@RestController
@RequestMapping("/cosFile")
@Api(value = "API", tags = {"腾讯云文件管理"})
public class CosUploadController {

    public static final String SECRET_ID = "AKID7D4fvuJXHl3293Agx1xo04NRUbU6Zn21";
    public static final String SECRET_KEY = "thGk1R9c2HG4c6JorgHoEVq3JVXT9hz3";
    public static final String REGION = "ap-beijing";
    public static final String BUCKET_NAME = "jingxing-1305712674";
    public static final String JINGXING_FILE = "JingXingCZY";
    public static final String COS_FILE_URL = "https://jingxing-1305712674.cos.ap-beijing.myqcloud.com/";


    /**
     * 上传单个腾讯云文件（公共）
     *
     * @return
     */
    @PostMapping("/JXUpload")
    @ApiOperation(value = "上传单个腾讯云文件（公共）")
    public ApiResult JXUpload(MultipartFile multipartFile,String route) throws Exception {
        String putObjectResult = getPutObjectResult(multipartFile,JINGXING_FILE,route);
        if (putObjectResult != null && !putObjectResult.equals("")) {
            return ApiResult.ok(COS_FILE_URL + putObjectResult);
        }
        return ApiResult.fail();
    }

    /**
     * 上传文件
     *
     * @param multipartFile
     * @param name
     * @return
     * @throws Exception
     */
    private String getPutObjectResult(MultipartFile multipartFile, String name,String route) throws Exception {
        COSClient cosClient = getCosClient();
        String dir = name + "/" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")) + "/";
        String filename = multipartFile.getOriginalFilename();
        String key ="";
        if(StringUtils.isNotBlank(route)){
            key = route+"/" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("HHmmssS")) + filename;
        }else {
            key = dir + LocalDateTime.now().format(DateTimeFormatter.ofPattern("HHmmssS")) + filename;
        }
        File file = multipartFileToFile(multipartFile);
        cosClient.putObject(BUCKET_NAME, key, file);
        return key;
    }

    /**
     * 初始化
     *
     * @return
     */
    private COSClient getCosClient() {
        // 1 初始化用户身份信息（secretId, secretKey）。
        COSCredentials cred = new BasicCOSCredentials(SECRET_ID, SECRET_KEY);
        // 2 设置 bucket 的区域, CI 地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
        // clientConfig 中包含了设置 region, https(默认 https), 超时, 代理等 set 方法, 使用可参见源码或者常见问题 Java SDK 部分。
        Region region = new Region(REGION);
        ClientConfig clientConfig = new ClientConfig(region);
        // 3 生成 cos 客户端。
        COSClient cosClient = new COSClient(cred, clientConfig);
        return cosClient;
    }

    /**
     * MultipartFile转换File
     *
     * @param file
     * @return
     * @throws Exception
     */
    private File multipartFileToFile(MultipartFile file) throws Exception {

        File toFile = null;
        if (file.equals("") || file.getSize() <= 0) {
            file = null;
        } else {
            InputStream ins = null;
            ins = file.getInputStream();
            toFile = new File(file.getOriginalFilename());
            inputStreamToFile(ins, toFile);
            ins.close();
        }
        return toFile;
    }

    //获取流文件
    private void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
